package pl.textureStudio.view.panel.manager
{
	import flash.display.DisplayObjectContainer;

	import actions.ActionsManager;

	import pl.textureStudio.view.panel.base.BasePanel;
	import pl.textureStudio.view.panel.base.IBasePanel;

	import flash.display.Sprite;
	import flash.events.Event;

	/**
	 * @author michalr
	 */
	public class PanelsManager extends Sprite implements IPanelManager
	{
		private var addedPanel:IBasePanel;
		private var newPanel:IBasePanel;
		private var chainID:String;

		public function PanelsManager()
		{
			addEventListener( Event.ADDED_TO_STAGE, onATS );
		}

		public static function factory( parent:DisplayObjectContainer ):IPanelManager
		{
			var o:PanelsManager = new PanelsManager();
			parent.addChild( o );
			return o as IPanelManager;
		}

		private function onATS( event:Event ):void
		{
			removeEventListener( Event.ADDED_TO_STAGE, onATS );
			init();
		}

		private function init():void
		{
			stage.addEventListener( Event.RESIZE, onSR );
			onSR();
		}

		private function onSR( event:Event = null ):void
		{
			x = Math.floor( stage.stageWidth * .5 );
			y = Math.floor( stage.stageHeight * .5 );
		}

		private function addPanel():void
		{
			if (addedPanel != null)
			{
				removeChild( addedPanel as Sprite );
				addedPanel.destroy();
			}
			addChild( newPanel as Sprite );
			addedPanel = null;
			addedPanel = newPanel;
			if (chainID != null)
				ActionsManager.runNextActionFromChain( chainID );
		}

		public function showPanel( panelID:String ):void
		{
			newPanel = BasePanel.factory( panelID );
			if (addedPanel == null)
			{
				addPanel();
			}
			else
			{
				if (panelID != addedPanel.panelID)
				{
					ActionsManager.addAction( hideCurrentPanel, "chowanie addedPanel" ).chainID( 'newPanel' ).fin();
					ActionsManager.addAction( addPanel, "dodanie panelu" ).chainID( 'newPanel' ).fin();
					ActionsManager.startChainByID( 'newPanel' );
				}
				else
				{
					trace( 'to juz bylo' );
				}
			}
		}

		public function set actionCompleteHandler( chainID:String ):void
		{
			this.chainID = chainID;
		}

		public function clearActionParticipation():void
		{
			this.chainID = null;
		}

		public function hideCurrentPanel():void
		{
			if (addedPanel != null)
			{
				removeChild( addedPanel as Sprite );
				addedPanel.destroy();
				addedPanel = null;
			}
			if (chainID != null)
				ActionsManager.runNextActionFromChain( chainID );
		}
	}
}
